package com.sumer.proxy.jdk;

import com.sumer.proxy.jdk.domain.Student;
import com.sumer.proxy.jdk.proxy.SimpleTransactions;
import com.sumer.proxy.jdk.proxy.StudentProxy;
import com.sumer.proxy.jdk.proxy.Transaction;
import com.sumer.proxy.jdk.proxy.cglib.proxy.CglibProxy;
import com.sumer.proxy.jdk.proxy.jdk.proxy.JDKProxy;
import com.sumer.proxy.jdk.service.StudentService;
import com.sumer.proxy.jdk.service.impl.StudentServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestProxy {

    public static void main(String[] args) {
        Transaction transaction = new SimpleTransactions();

//        StudentService o = (StudentService)Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[]{StudentService.class}, new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                Object result = null;
//                if ("add".equals(method.getName())) {
//                    transaction.begin();
//                    result = method.invoke(new StudentServiceImpl(), args);
//                    transaction.commit();
//                } else {
//                    result = method.invoke(new StudentServiceImpl(), args);
//                }
//                return result;
//            }
//        });
//        o.add(new Student("张三",32));

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(StudentServiceImpl.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                if ("add".equals(method.getName())) {
                    transaction.begin();
                    result = methodProxy.invokeSuper(o, objects);
                    transaction.commit();
                } else {
                    result = methodProxy.invokeSuper(o, objects);
                }
                return result;
            }
        });
        StudentService o = (StudentService) enhancer.create();
        o.add(new Student("张三",32));
    }
}
